package com.yunquan.ohana.ui.launcher

import android.Manifest
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityLauncherBinding
import com.yunquan.ohana.dialog.TipDialog
import com.yunquan.ohana.ui.guide.GuideActivity
import com.yunquan.ohana.utils.SPUtils
import java.util.Locale
import kotlin.system.exitProcess

class LauncherActivity : BaseActivity<ActivityLauncherBinding, LauncherViewModel>() {
    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_launcher
    }

    override fun initVariableId(): Int {
        return BR.launcherViewModel
    }

    override fun initParam() {
        super.initParam()
        Locale.setDefault(Locale("en"))
        // 设置背景颜色
        window.statusBarColor = ContextCompat.getColor(this, R.color.black)
        // 设置文字颜色（true = 黑色文字，false = 白色文字）
        val controller = WindowInsetsControllerCompat(window, window.decorView)
        controller.isAppearanceLightStatusBars = false
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        requestPhoneStatePermission()
    }

    private fun requestPhoneStatePermission() {
        phoneStatePermissionLauncher.launch(Manifest.permission.READ_PHONE_STATE)
    }

    private val phoneStatePermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { _ ->
        // 无论是否授权，都执行
        val first = SPUtils.getBoolean("firstStart", true)
        if (first) {
            startActivity(GuideActivity::class.java)
            finish()
        } else {
            viewModel!!.getUserInfo()
        }
    }

    private fun showNotDataDialog() {
        val dialog = TipDialog(this)
        dialog.setTitle(getString(R.string.connect_failed))
        dialog.setMessage(getString(R.string.tip_connect_failed))
        dialog.setLeftBtn(getString(R.string.btn_exit))
        dialog.setRightBtn(getString(R.string.btn_retry))
        dialog.setOnDialogClickListener(object : TipDialog.OnDialogClickListener() {
            override fun onLeftClick() {
                super.onLeftClick()
                exitProcess(0)
            }

            override fun onRightClick() {
                super.onRightClick()
            }
        })
        dialog.show()
    }
}